#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :register.py
# @Time      :2021/6/21 17:22
# @Author    : 刘广鸿

from url.urls import URLS
from config.config import shzx_app
from fastapi import Depends, status, Response
from sqlalchemy.orm import Session
from dbs import crud, mSession
from dbs import model
from dbs import schemas
from dbs.database import engine
import uuid
import hashlib
# import datetime
from time import time

# from random import randint

model.Base.metadata.create_all(bind=engine)

"""
    TEST FOR PUT METHOD:http://127.0.0.1:8000/register
    For user register
    
    params：  @user: schemas.UserCreate
    {
        username:str,
        password:str
    }
    
    return：
            301 for success
            304 for the username is existed
            422 for The parameters do not conform to the format
"""


@shzx_app.put(URLS[1])
def register(user: schemas.UserCreate, db: Session = Depends(mSession.get_db)):
    if crud.create_user(db, user):
        return Response(status_code=status.HTTP_301_MOVED_PERMANENTLY)
    else:
        return Response(status_code=status.HTTP_304_NOT_MODIFIED)


"""
    TEST FOR PUT METHOD:http://127.0.0.1:8000/registerDevice/{username}/{token}
    For user to create a device
    
    :params:  
     @deviceBase 
    {
        type: int,
        name: str,
        note: str
    }
    @username : who want to create the device
    @token: Verify the user's identity
    
    :return:  
        301 for success
        304 for fail
        422 for The parameters do not conform to the format
"""


@shzx_app.put(URLS[2])
def create_device(deviceBase: schemas.DeviceBase, username: str, token: str, db: Session = Depends(mSession.get_db)):
    uuids = str(uuid.uuid1())
    device = {
        "type": deviceBase.type,
        "name": deviceBase.name,
        "note": deviceBase.note,
        "uuid": uuids,
        "devices_key": hashlib.md5((uuids + "{0}".format(time())).encode("utf8")).hexdigest()
    }
    deviceCreate = schemas.DeviceCreate(**device)
    if crud.create_devices(db, username, token, deviceCreate):
        return Response(status_code=status.HTTP_301_MOVED_PERMANENTLY)
    else:
        return Response(status_code=status.HTTP_304_NOT_MODIFIED)


"""
    TEST FOR POST METHOD:http://127.0.0.1:8000/bind
    FOR user to bind the device
    :param 
        @BindDevice
        {
             username: str
             token: str
             uuid: str
             device_key: str
            }
    :return
        201 for bind success
        204 for bind fail
"""


@shzx_app.post(URLS[3])
def bind_device(bindDevice: schemas.BindDevice, db: Session = Depends(mSession.get_db)):
    if not crud.bind_devices(db, bindDevice):
        return Response(status_code=status.HTTP_204_NO_CONTENT)
    else:
        return Response(status_code=status.HTTP_201_CREATED)
